<template>
  <p>当前在线人数：{{ total }}</p>
  <van-cell-group inset>
    <van-field v-model="value" label="消息框" placeholder="请输入消息" />
  </van-cell-group>
  <div v-html="reply"></div>
  <van-button plain type="primary" @click="sendmsg">发送消息</van-button>
</template>

<script setup>
import { ref ,onBeforeUnmount} from "vue";
const selectitem = JSON.parse(localStorage.getItem("selectitem"));
let value = ref("");
let reply = ref("");
let total = ref(0);
const username = encodeURIComponent(selectitem.name);
//配置服务端IP地址
const webSocket = new WebSocket("wss://192.168.0.6:8080/chat?username=" + username);
/**
 * 当服务端打开连接
 */
webSocket.onopen = function (event) {
  console.log("WebSocket打开连接");
};
/**
 * 当服务端发来消息：1.广播消息 2.更新在线人数
 */
webSocket.onmessage = function (event) {
  console.log("WebSocket收到消息：%c" + event.data, "color:green");
  //获取服务端消息
  var message = JSON.parse(event.data) || {};
  reply.value += "<p>" + message.msg + "（" + message.username + "）</p>";
  console.log(reply.value);
  total.value = message.onlineCount;
};
/**
 * 关闭连接
 */
webSocket.onclose = function (event) {
  console.log("WebSocket关闭连接");
};

/**
 * 通信失败
 */
webSocket.onerror = function (event) {
  console.log("WebSocket发生异常");
};
function sendmsg() {
  showToast(value.value);
  webSocket.send(
    JSON.stringify({
      username: selectitem.name,
      msg: value.value,
      type: "SPEAK",
    })
  );
  value.value = "";
}

// 在组件卸载前关闭 WebSocket
onBeforeUnmount(() => {
  if (webSocket.readyState === WebSocket.OPEN) {
    webSocket.close(1000, '用户主动离开'); // 标准关闭码 1000
  }
});

// 监听浏览器标签关闭事件（保险措施）
window.addEventListener('beforeunload', () => {
  webSocket.close(1000, '页面关闭');
});
</script>

<style></style>
